package 二叉树._226;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 陈艺博
 * @date 2021-03-02 09:41
 * @description https://leetcode-cn.com/problems/invert-binary-tree/
 **/
public class _invert_binary_tree_翻转二叉树 {
    public TreeNode invertTree(TreeNode root) {
//        return preorderInvertTree(root);
//        return inorderInvertTree(root);
//        return postorderInvertTree(root);
        return levelOrderInvertTreeNode(root);
    }

    /**
     * 前序遍历反转二叉树
     */
    public TreeNode preorderInvertTree(TreeNode root) {
        //空则返回
        if (root == null) {
            return null;
        }

        //反转逻辑
        TreeNode tmpTreeNode = root.left;
        root.left = root.right;
        root.right = tmpTreeNode;

        // 前序遍历所有节点
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    /**
     * 后序遍历反转二叉树
     */
    public TreeNode postorderInvertTree(TreeNode root) {
        //空则返回
        if (root == null) {
            return null;
        }

        // 后序遍历所有节点
        invertTree(root.left);
        invertTree(root.right);

        //反转逻辑
        TreeNode tmpTreeNode = root.left;
        root.left = root.right;
        root.right = tmpTreeNode;

        return root;
    }

    /**
     * 使用中序遍历转换二叉树
     */
    public TreeNode inorderInvertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        // 遍历左
        inorderInvertTree(root.left);
        // 转换
        TreeNode node = root.left;
        root.left = root.right;
        root.right = node;
        // 遍历右，此时转换完，右到了左
        inorderInvertTree(root.left);
        return root;
    }

    /**
     * 使用层序转换二叉树
     */
    public TreeNode levelOrderInvertTreeNode(TreeNode root) {
        if (root == null) {
            return null;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();

            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;

            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return root;
    }
}
